/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.ytbolg.mcxa.util;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.ListSelectionModel;
import static javax.swing.ListSelectionModel.SINGLE_SELECTION;
import javax.swing.table.DefaultTableModel;
import net.ytbolg.mcxa.LangAndConfig.Lang;
import net.ytbolg.mcxa.Launcher.GameInfo;
import static net.ytbolg.mcxa.Launcher.GameInfo.tpf;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Ytong
 */
public class ForgeCheck extends javax.swing.JFrame {

    /**
     * Creates new form ForgeCheck
     */
    public ForgeCheck() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("下载Forge");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTable1.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane3.setViewportView(jTable1);

        jTabbedPane1.addTab("较新版本", jScrollPane3);

        jTable2.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable2.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable2);

        jTabbedPane1.addTab("较旧版本", jScrollPane1);

        jButton1.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jButton1.setText("下载");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jProgressBar1.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N

        jLabel1.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        DefaultTableModel newvm = (DefaultTableModel) jTable1.getModel();
        DefaultTableModel oldvm = (DefaultTableModel) jTable2.getModel();

        String mcver = "";
        String ver = "";
        
        switch (jTabbedPane1.getSelectedIndex()) {
            case 0: {
                //            System.out.println(jTable1.getValueAt(jTable1.getSelectedRow(), 0));
                //   System.out.println(jTable2.getSelectedRow());
                ver = newvm.getValueAt(jTable1.getSelectedRow(), 0).toString();
                mcver = newvm.getValueAt(jTable1.getSelectedRow(), 1).toString();
               new net.ytbolg.mcxa.Output.Logger(0).Log("Select forge version:"+ver+",mc version"+mcver);
                break;
                //    System.out.println(ver + mcver);
            }
            case 1: {
                ver = oldvm.getValueAt(jTable2.getSelectedRow(), 0).toString();
                mcver = oldvm.getValueAt(jTable2.getSelectedRow(), 1).toString();
             new net.ytbolg.mcxa.Output.Logger(0).Log("Select forge version:"+ver+",mc version"+mcver);
                break;
                // System.out.println(ver + mcver);
            }

        }
        DownloadForge.version = mcver;
        DownloadForge.forgeversion = ver;
        DownloadForge.j = jProgressBar1;
        DownloadForge.l = jLabel1;
        new Thread(new DownloadForge()).start();        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated

    }//GEN-LAST:event_formWindowActivated

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        jTable1.setColumnSelectionAllowed(false);
        jTable2.setColumnSelectionAllowed(false);

        jTable1.setRowSelectionAllowed(true);
        jTable2.setRowSelectionAllowed(true);

        setTitle(Lang.getLang("Forge_Window_Loading"));
        jButton1.setText(Lang.getLang("Forge_Button_Download"));
        jTabbedPane1.setTitleAt(0, Lang.getLang("Forge_TabledPanel_OlderVersion"));
        jTabbedPane1.setTitleAt(1, Lang.getLang("Forge_TabledPanel_NewerVersion"));

        DefaultTableModel newvm = (DefaultTableModel) jTable1.getModel();
        DefaultTableModel oldvm = (DefaultTableModel) jTable2.getModel();
        newvm.addColumn(Lang.getLang("Forge_Table_ForgeVer"));
        newvm.addColumn(Lang.getLang("Forge_Table_McVer"));
        newvm.addColumn(Lang.getLang("Forge_Table_RelTime"));
        oldvm.addColumn(Lang.getLang("Forge_Table_ForgeVer"));
        oldvm.addColumn(Lang.getLang("Forge_Table_McVer"));
        oldvm.addColumn(Lang.getLang("Forge_Table_RelTime"));
        jTable1.setSelectionMode(SINGLE_SELECTION);
        jTable2.setSelectionMode(SINGLE_SELECTION);

        JSONArray newv = null;
        try {
            newv = new JSONArray(downloadFile("http://bmclapi.bangbang93.com/forge/versionlist"));
        } catch (JSONException ex) {
            Logger.getLogger(ForgeCheck.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ForgeCheck.class.getName()).log(Level.SEVERE, null, ex);
        }
        JSONArray oldv = null;
        try {
            oldv = new JSONArray(downloadFile("http://bmclapi.bangbang93.com/forge/legacylist"));
        } catch (JSONException ex) {
            Logger.getLogger(ForgeCheck.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ForgeCheck.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (int i = 0; i < newv.length(); i++) {
            try {
                JSONObject jo = newv.getJSONObject(i);
                newvm.addRow(new Object[]{jo.get("ver"), jo.get("mcver"), jo.get("releasetime")});
            } catch (JSONException ex) {
                //    Logger.getogger(ForgeDownloader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        for (int i = 0; i < oldv.length(); i++) {
            try {
                JSONObject jo = oldv.getJSONObject(i);
                oldvm.addRow(new Object[]{jo.get("ver"), jo.get("mcver"), jo.get("releasetime")});
            } catch (JSONException ex) {
                //    Logger.getogger(ForgeDownloader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        setTitle(Lang.getLang("Forge_Title"));// TODO add your handling code here:        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowOpened


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables
  public static String downloadFile(String remoteFilePath) throws IOException {

        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;


//      f.mkdirs();
        try {
            StringBuilder sb = new StringBuilder();
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            //   bis = new BufferedInputStream(httpUrl.getInputStream());
            InputStreamReader isr = new InputStreamReader(httpUrl.getInputStream());
            //    bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 0;
            //byte[] b = new byte[len];
            while ((len =isr.read()) != -1) {
                //        bos.write(b, 0, len);
                sb.append((char) len);
            }
         //   bos.flush();
            isr.close();
// bis.close();
            httpUrl.disconnect();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }

    }

    static String ReadFile(String path) throws FileNotFoundException, IOException {

        File file = new File(path);
        FileReader r = new FileReader(file);
        char c[] = new char[(int) file.length()];
        r.read(c);

        r.close();
        return String.valueOf(c);
    }
}

class DownloadForge implements Runnable {

    public static String version = "";
    public static JProgressBar j;
    public static JLabel l;
    public static String forgeversion = "";

    //@Override
    @Override
    public void run() {
         new net.ytbolg.mcxa.Output.Logger(0).Log(Lang.getLang("Forge_StartDown") + "http://bmclapi.bangbang93.com/forge/getforge" + "/" + version + "/" + forgeversion);
        downloadFile("http://bmclapi.bangbang93.com/forge/getforge" + "/" + version + "/" + forgeversion, GameInfo.Rundir + tpf + "forgetmp.jar");
        //   downloadFile("http://bmclapi.bangbang93.com/versions/" + version + "/" + version + ".json", GameInfo.GameDir + tpf + "versions" + tpf + version + tpf + version + ".json");
        JOptionPane.showMessageDialog(null, Lang.getLang("Forge_DownSucc"));
        j.setValue(0);
        l.setText("");
        JOptionPane.showMessageDialog(null, Lang.getLang("Forge_SetupForge"));
        Clipboard clipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
        //  String vc = refContent.trim();  
        //  StringSelection ss = new StringSelection(vc);  

        StringSelection selection = new StringSelection(GameInfo.GameDir);//复制step1:生成Transferable 接口对象。剪贴板只能放该类型的对象。 StringSelection类实现了Transferable接口。
        clipBoard.setContents(selection, null);//复制step2.第二个参数是Owner。
        try {
            Runtime.getRuntime().exec("java -jar " + GameInfo.Rundir + tpf + "forgetmp.jar");
//  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        } catch (IOException ex) {
            Logger.getLogger(DownloadForge.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void downloadFile(String remoteFilePath, String localFilePath) {
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        File xxxx = new File(f.getParent());
        xxxx.mkdirs();

//      f.mkdirs();
        try {
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            j.setMaximum(httpUrl.getContentLength());
            j.setValue(0);
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            int i = 0;
            while ((len = bis.read(b)) != -1) {
                i = i + len;
                j.setValue(i);
                l.setText(i / 1024 + "/" + (httpUrl.getContentLength() / 1024) + "KB");
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
